<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="powerName">
        <el-input
          v-model="queryParams.powerName"
          placeholder="请输入职权名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="powerDuties">
        <el-select v-model="queryParams.powerDuties" placeholder="请选择职务" clearable size="small">
          <el-option
            v-for="dict in powerDutiesOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入顺序号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:powers:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:powers:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:powers:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:powers:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="powersList"
      @selection-change="handleSelectionChange"
      :stripe="true"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" header-align="center" align="center" width="150" prop="index" />
      <el-table-column label="职权名称"  align="left" prop="powerName" :show-overflow-tooltip="true" />
      <el-table-column label="职务" align="left" prop="powerDuties" :show-overflow-tooltip="true"/>
      <el-table-column label="顺序号"  align="right" width="150" prop="orderNo" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" header-align="center" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:powers:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:powers:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改职权信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="职权名称" prop="powerName">
              <el-input v-model="form.powerName" placeholder="请输入职权名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顺序号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入顺序号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="powerDuties">
              <el-select multiple v-model="form.powerDuties" placeholder="请选择职务">
                <el-option
                  v-for="dict in powerDutiesOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPowers, getPowers, delPowers, addPowers, updatePowers, exportPowers } from "@/api/system/powers";
import { export_json_to_excel } from '@/excel/Export2Excel'

export default {
  name: "Powers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 职权信息表格数据
      powersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 职务字典
      powerDutiesOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        powerName: null,
        powerDuties: null,
        orderNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        powerName: [
          { required: true, message: "职权名称不能为空", trigger: "blur" }
        ],
        powerDuties: [
          { required: true, message: "职务不能为空", trigger: "change" }
        ],
        orderNo: [
          { required: true, message: "顺序号不能为空", trigger: "blur" }
        ],
      },
      orderNos:[]
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_position").then(response => {
      this.powerDutiesOptions = response.data;
    });
  },
  methods: {
    /** 查询职权信息列表 */
    getList() {
      this.loading = true;
      listPowers(this.queryParams).then(response => {
        this.powersList = response.rows;
        this.powersList.forEach((item,i) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + i + 1
        })
        this.orderNos = this.powersList.map(item => item.orderNo)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 职务字典翻译
    powerDutiesFormat(row, column) {
      // console.log(this.powerDutiesOptions)
      return this.selectDictLabel(this.powerDutiesOptions, row.powerDuties);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recNo: null,
        powerName: null,
        powerDuties: null,
        delFlag: null,
        orderNo: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recNo)
      this.names = selection.map(item => item.powerName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.orderNo = Math.max.apply(null,this.orderNos) + 1
      this.open = true;
      this.title = "添加职权信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recNo = row.recNo || this.ids
      getPowers(recNo).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改职权信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.powerDuties = this.form.powerDuties.join(',')
          console.log(this.form.powerDuties)
          if (this.form.recNo != null) {
            updatePowers(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPowers(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recNos = row.recNo || this.ids;
      const powerName = row.powerName || this.names;
      this.$confirm('是否确认删除职权信息名称为"' + powerName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPowers(recNos);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出职权信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
        const res = await listPowers()
        let Lis = res.rows
        if(this.ids.length > 0){
          Lis = this.powersList.filter(item => this.ids.indexOf(item.recNo) !== -1)
        }
        // console.log(Lis,this.ids)
        require.ensure([], () => {
          const { export_json_to_excel } = require('../../../excel/Export2Excel');
          const tHeader = ['职权名称', '职务', '顺序号'];
          const filterVal = ['powerName', 'powerDuties', 'orderNo'];
          const list = Lis;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, '职权管理');
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
      /*.then(function(){
          // return  exportPowers(queryParams);
          this.export2Excel()
        }).then(response => {
        // this.download(response.msg);
      }) */
    },
    //  按需导出
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }

  }
};
</script>
<style lang="scss" scoped>

</style>
